// 使用UMD版本的LiveKit客户端
// 确保在index.html中引入了LiveKit客户端的UMD版本

// 等待LiveKit客户端加载完成
window.addEventListener('DOMContentLoaded', () => {
  // 动态加载LiveKit客户端
  const script = document.createElement('script');
  script.src = 'https://cdn.jsdelivr.net/npm/livekit-client@2.0.9/dist/livekit-client.umd.min.js';
  script.onload = initApp;
  script.onerror = () => {
    console.error('加载LiveKit客户端失败');
    document.getElementById('status').textContent = '状态: 加载LiveKit客户端失败';
  };
  document.head.appendChild(script);
});

function initApp() {
  // 固定的元素引用
  const localVideo = document.getElementById('localVideo');
  const btnPublish = document.getElementById('btnPublish');
  const btnStop = document.getElementById('btnStop');
  const statusEl = document.getElementById('status');

  // 固定的配置
  const ROOM_NAME = 'room1';
  const USER_NAME = 'user1';
  // 使用当前主机名而不是硬编码localhost
  const WS_URL = `ws://${window.location.hostname}:7880`;

  // 正确格式的JWT token
  const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjQ4MjI0ODkwODksImlzcyI6ImRldmtleSIsIm5hbWUiOiJ1c2VyMSIsInN1YiI6InVzZXIxIiwicm9vbSI6InJvb20xIn0.KVVEWMXv9SsJcZ5eFJdKYiUYHYMdGzTNFDFYUHj9cV0';

  // LiveKit 房间实例
  let room = new LivekitClient.Room();
  let isConnected = false;

  // 更新状态显示
  function updateStatus(message) {
    statusEl.textContent = `状态: ${message}`;
    console.log(message);
  }

  // 连接到 LiveKit 房间
  async function connectToRoom() {
    try {
      updateStatus('正在连接到 LiveKit 服务器...');
      console.log(`尝试连接到: ${WS_URL}`);
      
      await room.connect(WS_URL, TOKEN, {
        autoSubscribe: true
      });
      
      isConnected = true;
      updateStatus(`已连接到房间: ${ROOM_NAME}`);
      return true;
    } catch (err) {
      updateStatus(`连接失败: ${err.message}`);
      console.error('连接错误:', err);
      alert(`连接错误: ${err.message}\n请检查LiveKit服务器是否正常运行。`);
      return false;
    }
  }

  // 开始推流
  async function startPublishing() {
    try {
      btnPublish.disabled = true;
      
      // 如果尚未连接，先连接
      if (!isConnected) {
        const connected = await connectToRoom();
        if (!connected) {
          btnPublish.disabled = false;
          return;
        }
      }
      
      updateStatus('正在获取摄像头和麦克风权限...');
      
      try {
        // 获取媒体设备
        const mediaStream = await navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true
        });
        
        // 显示本地预览
        localVideo.srcObject = mediaStream;
        
        // 发布视频和音频轨道
        updateStatus('正在发布音视频流...');
        
        // 创建并发布轨道
        const videoTrack = mediaStream.getVideoTracks()[0];
        const audioTrack = mediaStream.getAudioTracks()[0];
        
        if (videoTrack) {
          await room.localParticipant.publishTrack(videoTrack);
        }
        
        if (audioTrack) {
          await room.localParticipant.publishTrack(audioTrack);
        }
        
        updateStatus('✅ 推流成功！WebRTC 流已发布，正在转推到 RTMP');
        btnStop.disabled = false;

        // 自动设置RTMP转推
        setupRtmpEgress();
        
      } catch (mediaErr) {
        updateStatus(`获取媒体设备失败: ${mediaErr.message}`);
        console.error('媒体设备错误:', mediaErr);
        alert('无法访问摄像头或麦克风，请确保已授予权限。');
        btnPublish.disabled = false;
      }
    } catch (err) {
      updateStatus(`推流失败: ${err.message}`);
      console.error('推流错误:', err);
      btnPublish.disabled = false;
    }
  }

  // 停止推流
  async function stopPublishing() {
    try {
      btnStop.disabled = true;
      
      // 停止所有轨道
      if (localVideo.srcObject) {
        localVideo.srcObject.getTracks().forEach(track => track.stop());
        localVideo.srcObject = null;
      }
      
      // 断开连接
      if (isConnected) {
        await room.disconnect();
        isConnected = false;
      }
      
      updateStatus('已停止推流');
      btnPublish.disabled = false;
    } catch (err) {
      updateStatus(`停止推流失败: ${err.message}`);
      console.error('停止推流错误:', err);
      btnStop.disabled = false;
    }
  }

  // 设置RTMP转推
  async function setupRtmpEgress() {
    try {
      updateStatus('正在设置RTMP转推...');
      
      // 构建请求数据
      const data = {
        room_name: 'room1',
        layout: 'grid',
        audio_only: false,
        video_only: false,
        output: {
          rtmp: {
            urls: ['rtmp://rtmp:1935/live/room1']
          }
        }
      };
      
      // 发送请求
      const response = await fetch(`http://${window.location.hostname}:8080/room_composite/rtmp`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      
      if (response.ok) {
        const result = await response.json();
        console.log('RTMP转推设置成功:', result);
        updateStatus('✅ 推流成功！WebRTC流已发布，RTMP转推已设置');
      } else {
        const error = await response.text();
        console.error('RTMP转推设置失败:', error);
        updateStatus('✅ 推流成功！但RTMP转推设置失败');
      }
    } catch (err) {
      console.error('RTMP转推设置错误:', err);
      updateStatus('✅ 推流成功！但RTMP转推设置出错');
    }
  }

  // 初始化
  function init() {
    btnPublish.onclick = startPublishing;
    btnStop.onclick = stopPublishing;
    btnStop.disabled = true;
    updateStatus('准备就绪，点击"开始推流"按钮开始');
    
    // 添加调试信息
    console.log('LiveKit WebRTC 推流页面已加载');
    console.log(`房间名: ${ROOM_NAME}`);
    console.log(`用户名: ${USER_NAME}`);
    console.log(`WebSocket URL: ${WS_URL}`);
  }

  // 启动
  init();
}